from collections import deque, defaultdict


class Twitter2:
    def __init__(self):
        self.user_follow = defaultdict(set)
        self.tweet = deque()

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.tweet.appendleft([tweetId, userId])

    def getNewsFeed(self, userId: int) -> list:
        res, user_follow = [], self.user_follow[userId]
        for tweet in self.tweet:
            if tweet[1] == userId or tweet[1] in user_follow:
                res.append(tweet[0])
                if len(res) == 10:
                    break
        return res

    def follow(self, followerId: int, followeeId: int) -> None:
        self.user_follow[followerId].add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        try:
            self.user_follow[followerId].remove(followeeId)
        except:
            pass


"""-----------------------------------------------------------------------------------------"""


class User(object):
    def __init__(self, id):
        self.id = id
        self.tweet = []
        self.follow = set()


class Twitter:
    def __init__(self):
        self.user_dict = dict()
        self.tweet_count = 0
        self.tweet_dict = defaultdict(int)

    def __get_user(self, id):
        if id not in self.user_dict:
            user = User(id)
            self.user_dict[id] = user
        else:
            user = self.user_dict[id]
        return user

    def postTweet(self, userId: int, tweetId: int) -> None:
        user = self.__get_user(userId)
        self.tweet_count += 1
        self.tweet_dict[tweetId] = self.tweet_count
        user.tweet.append(tweetId)

    def getNewsFeed(self, userId: int) -> list:
        user = self.__get_user(userId)
        res = user.tweet[:]
        for follower in user.follow:
            res.extend(follower.tweet)
        res.sort(key=lambda x: self.tweet_dict[x], reverse=True)
        return res[:10]

    def follow(self, followerId: int, followeeId: int) -> None:
        if followerId == followeeId:
            return
        follower = self.__get_user(followerId)
        followed = self.__get_user(followeeId)
        follower.follow.add(followed)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        follower = self.__get_user(followerId)
        followed = self.__get_user(followeeId)
        try:
            follower.follow.remove(followed)
        except:
            pass


# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId)

a = Twitter()
a.postTweet(1, 5)
print(a.getNewsFeed(1))
a.follow(1, 2)
a.postTweet(2, 6)
print(a.getNewsFeed(1))
a.unfollow(1, 2)
print(a.getNewsFeed(1))
